<template>
  <div class="radar-gadget-css" style="width:100%;height:100%" :id="id">

    <Portal to="right-disable" style="width:100%;height:100%;"
            v-loading="loading"
            :disabled="!queryModelDefaultSetting.showSetting">
      <DashboardInterceptConsumer :gadgetId="id"
                                  shadow="hover"
                                  @mouseenter="mouseenter(true)"
                                  @mouseleave="mouseenter(false)"
                                  style="width:100%;height: 100%;border:0">
        <el-card shadow="never"
                 style="width:100%;height: 100%;border:0"
                 class="aui-card--fill">
          <div style="width:100%;height:100%;">
            <div class="cardHeader"
                 @mouseenter="mouseenter(true)"
                 @mouseleave="mouseenter(false)"
                 v-if="(widgetName && widgetName.trim().length>0) || (gadgetSetting&&gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">
              <GadgetTitle :gadgetSetting="gadgetSetting"
                           :widgetName="widgetName"></GadgetTitle>
              <div>
                <MoreMenu :slicer='slicer'
                          :fitToHeight='fitToHeight'
                          :gadgetId='id'
                          :gadgetType='gadgetInfo.com'
                          @updateQuery="query"
                          :widgetName="widgetName"
                          :businessType="gadgetInfo.businessType"
                          :id="gadgetInfo.id"
                          @showQueryModel="showQueryModel"
                          @fullScreen="fullScreen" />
              </div>
            </div>
            <div class="control-section control-section2">
              <div class=content-wrapper
                   style="width:100%;height:100%;">
                <div v-if="isHasData"
                  style="width:100%;height:100%;">
                  <div style="height:30px;line-height: 30px;font-size:16px;font-weight:700;text-align:center">{{gadgetSetting.title}}</div>
                  <div :id="selfGadgetUuid" style="width:100%;height:calc(100% - 30px);"></div>
                </div>
                <div v-else
                     class="gadget-no-newdata">
                    <div class="widgets-no-data">
                    <div :style="{'fontSize':fontSizeStr1}">{{$t('custom.component.gadget.nodata')}}</div>
                    <div class="widgets-tip"> <a :href="widgetNoDataWiki"  :style="{'fontSize':fontSizeStr2}"
                         target="black">{{$t('custom.component.gadget.nodatatip')}}</a> </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
        <Lastupdatetime v-if="currentTime"
                        :currentTime="currentTime"
                        :linkedDatasetList="linkedDatasetList"
                        :errorStatus="errorStatus"
                        @updateQuery="query()"></Lastupdatetime>
      </DashboardInterceptConsumer>

    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           :slicer='slicer' />
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :slicer="slicer"
                  :queryId="queryId"
                  ref="drill-through"
                  :widgetName='widgetName' />
    <div style="position:absolute;left:9999px;">
      <component v-for="(item, index) in formatComponentList"
                 :key="index"
                 :is="item"
                 :ref="item"
                 gadgetType='notgridgadget' />
    </div>
  </div>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import { defaultGadgetSettingList } from '@/utils/data-json'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'
import * as Echarts from 'echarts'
import { getUUID } from '@/utils'
export default ({
  mixins: [mixinGadgetViewModule, mixinFormatViewModule],
  components: { Lastupdatetime, model: () => import('@/components/gadget/query-model/query-model') },
  data: function () {
    return {
      selfGadgetUuid: getUUID(),
      repeatNumber: 0,
      chartOption: {
        color: [],
        animation: 'auto',
        title: {
          text: '',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a}<br />{b}: {c}'
        },
        legend: {
          type: 'scroll',
          top: 20,
          width: '90%',
          data: []
        },
        grid: {
          top: '11%',
          left: '10px',
          right: '10px',
          bottom: '10px',
          width: '95%',
          // height: '85%',
          containLabel: true
        },
        radar: {
          // shape: 'circle',
          indicator: [
           
          ]
        }, 
        series: []
      },
      chartDom: null,
      currentTime: null,
      queryData: [],
      queryFields: [],
      theme: 'Material',
      dataSource: [{ name: 'a', data: [{ x: 0, y: 0 }] }],
      gadgetSetting: null,
      loading: false,
      chartWidth: '600px',
      dataSource1: null,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'radarchartgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'radarchartgadget' }).gadgetSetting
        }
      },
      queryId: '',
      queryDrillthrough: {},
      queryDrillthroughList: [],
      selectFields: [],
      widgetName: '',
      conditionFormat: [],
      linkedDatasetList: []
    }
  },
  beforeCreate () {
 
  },
  created () {
    this.gadgetHeight = (this.gadgetInfo.h * 20) - 45
    // this.query()
    this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    })
    this.$store.state.isWidget = false
  },
  methods: {
    updateChart (originData) {
      var _self = this
      _self.chartDom = document.getElementById(`${_self.selfGadgetUuid}`)
      if (!_self.chartDom) {
        setTimeout(() => {
          _self.repeatNumber++
          _self.updateChart(originData)
        }, 1000)
      } else if (
        !Array.isArray(originData) ||
        (Array.isArray(originData) && originData.length === 0)
      ) {
        Echarts.init(_self.chartDom).dispose()
      } else {
        _self.chartOption = _self.$options.data.call(_self).chartOption
        _self.repeatNumber = 0
        let myChart = Echarts.init(_self.chartDom, this.globalTheme)
        this.setChartOption()
        myChart.setOption(_self.chartOption)
        myChart.on('click', params => {
              if (_self.chartOption.radar.indicator[params.event.topTarget.__dimIdx]&& _self.chartOption.radar.indicator[params.event.topTarget.__dimIdx].name ) {
                  params.seriesName = _self.chartOption.radar.indicator[params.event.topTarget.__dimIdx].name
              }
              params.name = params.data.name
              this.queryId = this.queryFields.find(ii=>ii.bind===params.seriesName)&&this.queryFields.find(ii=>ii.bind===params.seriesName).queryId
              if (this.queryFields.filter(ii=>ii.dataType==='dimension').length !== 0) {
                _self.setDrillThroughInfo(params)
              } else {
                _self.findOriginData('')
              }
        })     
        _self.$erd.listenTo(_self.chartDom, element => {
          _self.$nextTick(() => {
            _self.resized()
          })
        })
      }
    },
    setChartOption () {
      const _self = this
      _self.chartOption = {
        legend: _self.setLegend(),
        radar: _self.setRadar(),
        series: _self.setSeries(),
        tooltip: {
          show:true,
          formatter: params => {
            let arr = []
            this.gadgetSetting.valueFieldsNameManyY.forEach((item,index)=>{
              arr.push(
                item,this.setFormatFunctionForChart(this.queryFields, params.value[index], item)
              )
            })
            let outputString = '';
            for (let i = 0; i < arr.length; i++) {
               if (i % 2 === 0) {
                 outputString += arr[i] + ' : ';
               } else {
                 outputString += arr[i] + '<br />';
               }
              }
            return this.setFormatFunctionForChart(this.queryFields, params.name, this.gadgetSetting.valueFieldsNameMeasureX)? `${this.setFormatFunctionForChart(this.queryFields, params.name, this.gadgetSetting.valueFieldsNameMeasureX)} <br /> ${outputString}` : `${outputString}`
          }
        },
      }
    },
    setLegend() {
      const _self = this
      let legendData = []
      this.queryData.forEach(item=>{
        legendData.push(
         `${item[this.gadgetSetting.valueFieldsNameMeasureX]}`
        )
      })
      return  {
        formatter: function (name, series) {
          return _self.setFormatFunctionForChart(_self.queryFields, name, _self.gadgetSetting.valueFieldsNameMeasureX)
        },
        data: legendData,
        type: 'scroll',
        top: 10,
        bottom:10,
        width: '60%',
      }
    },
    setRadar() {
      let indicatorData = []
      this.gadgetSetting.valueFieldsNameManyY.forEach(item=>{
        this.queryFields.forEach(ii=>{
          if(item===ii.alias&&ii.dataType==='measure') {
            indicatorData.push({
              name:item,
              axisLabel: {
               formatter: value => {
                  return `${this.setFormatFunctionForChart(this.queryFields, value, item)}`
                }
              }
            })
          }
        })
       
      })

      return {
        axisLabel:{
          show: this.gadgetSetting.axisLabel,
        },
        indicator : indicatorData,
        center: ['50%', '55%']
      }

    },
    setSeries () {
      let seriesData = this.queryData.map(item => {
        return {
          value: this.gadgetSetting.valueFieldsNameManyY.map(key => item[key]),
          name:`${item[this.gadgetSetting.valueFieldsNameMeasureX]}`
        }
      })
      let seriesDataName = this.queryData.map(item => {return item[this.gadgetSetting.valueFieldsNameMeasureX]})
      return {
        name:seriesDataName,
        type:'radar',
        data:seriesData
      }
    },

    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      setTimeout(() => {
        let myChart = Echarts.init(this.chartDom, this.globalTheme)
        myChart.resize()
      }, 0)
    },
    containerResizedEvent (i, newH, newW, newHPx, newWPx) {
      this.chartWidth = (newWPx - 10) + 'px'
    },
    upgradeGadgetSetting (setting) {

    },
    query (e) {
      this.gadgetSetting = this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      if (e !== 'auto') {
        this.loading = true
      }
      var _self = this
      var obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (tempObj['name'] && this.slicer['name'] && tempObj['name'] === this.slicer['name']) delete this.slicer['name']
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      var param = {
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      _self.queryData = []
      this.$interface.reports.getReportDataInfo(param).then(({ data: res }) => {
        try {
          _self.$parent.$parent.$parent.$parent.$parent.$parent.selectFields = res.selectFields
        } catch (error) {

        }
        _self.verifyHasData(res)
        if (res.config) {
          _self._.merge(_self.gadgetSetting, res.config)
          if (!_self.gadgetSetting.headerDescription || _self.gadgetSetting.headerDescription === null) {
            _self.gadgetSetting.headerDescription = ''
          }
          _self.upgradeGadgetSetting(_self.gadgetSetting)
        }

        if (res.name) {
          _self.widgetName = res.name
        } else if (this.wName) {
           _self.widgetName = this.wName
        }  else {
          _self.widgetName = _self.gadgetSetting.headerTitle
        }
        this.fxFields = res.fxFields || []
        if (res.data) {
          
          this.currentTime = new Date()
          _self.queryData = res.data
          _self.queryFields = res.selectFields
          _self.conditionFormat = res.conditionFormat.reverse()
          _self.linkedDatasetList = res.datasetSync
          if (_self.queryData) {
              _self.updateChart(_self.queryData)
          }
        }
      }).catch((error) => {
          if (this.wName) {
          this.widgetName = this.wName
        }
        Echarts.init(_self.chartDom).dispose()
        _self.isHasData = false
        _self.loading = false
        if (error.response && error.response.status === 504) {
          this.errorStatus = '504'
          this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
        }
      }).finally(() => {
        this.currentTime = new Date()
        this.autoRefreshQuery(e)
        this.updateGadgetLoadingStatus(!this.loading)
      })
    }
  }
})
</script>
<style lang="scss" scoped>
.content-wrapper {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 40%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}
</style>
<style scoped>
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardTitle {
  font-size: 16px;
  color: #000;
  font-weight: 700;
  display: inline-block;
  max-width: calc(100% - 30px);
  position: relative;
  top: 2px;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}
</style>
<style lang="scss">
.radar-gadget-css {
  .el-card__body {
    width: 100%;
    height: 100%;
  }
  .control-section2 {
    width: 100%;
    height: calc(100% - 34px);
  }
}
</style>
